﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Threading;
using System.Xml.Linq;
using System.Collections;
using Telerik.Windows.Controls;
using System.Windows.Browser;
namespace et_test
{
    public partial class Survey : UserControl
    {        
        // 异常信息
        string _exception = "";
        // SynchronizationContext - 同步上下文管理类
        SynchronizationContext _syncContext;

        List<SurveyModel> surveyCollections = new List<SurveyModel>();

        int surveryid = -1;
        string content = "";
        string comment = "";

        public Survey(int examid, int categoryid)
        {
            InitializeComponent();
            try
            {
                string _url = string.Format("http://{0}/tools/ajax.aspx?t=getSurveyInfo&id={1}&cid={2}", App.Current.Host.Source.AbsoluteUri.Split('/')[2], examid, categoryid);
                GetXML(_url);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
            }
        }



        #region request
        void GetXML(string url)
        {
            // SynchronizationContext.Current - 当前线程的同步上下文
            _syncContext = SynchronizationContext.Current;
            /*

             * HttpWebRequest - 对指定的 URI 发出请求

             *     HttpWebRequest.Create(uri) - 初始化一个 WebRequest

             *     HttpWebRequest.BeginGetResponse(AsyncCallback callback, Object state) - 开始对指定 URI 资源做异步请求

             *         AsyncCallback callback - System.AsyncCallback 委托。异步操作完成时调用的回调方法

             *         Object state - 包含此异步请求的对象。即相应的 HttpWebRequest 对象

             *     HttpWebRequest.Abort() - 取消该异步请求

             *     HttpWebRequest.Accept - HTTP 头的 Accept  部分

             *     HttpWebRequest.ContentType - HTTP 头的 ContentType 部分

             *     HttpWebRequest.Headers - HTTP 头的 key/value 对集合

             *     HttpWebRequest.Method - HTTP 方法（只支持GET和POST）

             *     HttpWebRequest.RequestUri - 所请求的 URI

             *     HttpWebRequest.HaveResponse - 是否接收到了指定 URI 的响应

             *     HttpWebRequest.AllowReadStreamBuffering - 是否对从 Internet 资源接收的数据做缓冲处理。默认值为true，将数据缓存在客户端内存中，以便随时被应用程序读取

             */
            HttpWebRequest request = WebRequest.Create(
                new Uri(url, UriKind.Absolute)) as HttpWebRequest;
            request.Method = "GET";
            request.BeginGetResponse(new AsyncCallback(ResponseCallback), request);

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="result">IAsyncResult.AsyncState - AsyncCallback 传过来的对象</param>
        private void ResponseCallback(IAsyncResult result)
        {
            HttpWebRequest request = result.AsyncState as HttpWebRequest;
            WebResponse response = null;
            try
            {
                // HttpWebRequest.EndGetResponse(IAsyncResult) - 结束对指定 URI 资源做异步请求
                //     返回值为 WebResponse 对象
                response = request.EndGetResponse(result) as HttpWebResponse;
            }
            catch (Exception ex)
            {
                _exception = ex.ToString();
            }
            // SynchronizationContext.Post(SendOrPostCallback d, Object state) - 将异步消息发送到该同步上下文中
            //     SendOrPostCallback d - System.Threading.SendOrPostCallback 委托
            //     Object state - 需要传递的参数
            _syncContext.Post(GetResponse, response);
        }

        /// <summary>
        /// HttpWebResponse - 对指定的 URI 做出响应
        /// GetResponseStream() - 获取响应的数据流
        /// </summary>
        /// <param name="state"></param>
        private void GetResponse(object state)
        {
            HttpWebResponse response = state as HttpWebResponse;
            if (response != null)
            {
                Stream responseStream = response.GetResponseStream();
                using (StreamReader sr = new StreamReader(responseStream))
                {
                    string xml = sr.ReadToEnd();
                    getSurveyInfo(xml);
                }
            }
            else
            {
                MessageBox.Show(_exception);
            }

        }



        void SetXML(string url)
        {
            // SynchronizationContext.Current - 当前线程的同步上下文
            _syncContext = SynchronizationContext.Current;
            /*

             * HttpWebRequest - 对指定的 URI 发出请求

             *     HttpWebRequest.Create(uri) - 初始化一个 WebRequest

             *     HttpWebRequest.BeginGetResponse(AsyncCallback callback, Object state) - 开始对指定 URI 资源做异步请求

             *         AsyncCallback callback - System.AsyncCallback 委托。异步操作完成时调用的回调方法

             *         Object state - 包含此异步请求的对象。即相应的 HttpWebRequest 对象

             *     HttpWebRequest.Abort() - 取消该异步请求

             *     HttpWebRequest.Accept - HTTP 头的 Accept  部分

             *     HttpWebRequest.ContentType - HTTP 头的 ContentType 部分

             *     HttpWebRequest.Headers - HTTP 头的 key/value 对集合

             *     HttpWebRequest.Method - HTTP 方法（只支持GET和POST）

             *     HttpWebRequest.RequestUri - 所请求的 URI

             *     HttpWebRequest.HaveResponse - 是否接收到了指定 URI 的响应

             *     HttpWebRequest.AllowReadStreamBuffering - 是否对从 Internet 资源接收的数据做缓冲处理。默认值为true，将数据缓存在客户端内存中，以便随时被应用程序读取

             */
            HttpWebRequest request = WebRequest.Create(
                new Uri(url, UriKind.Absolute)) as HttpWebRequest;
            request.Method = "GET";
            request.BeginGetResponse(new AsyncCallback(ResponseCallback2), request);

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="result">IAsyncResult.AsyncState - AsyncCallback 传过来的对象</param>
        private void ResponseCallback2(IAsyncResult result)
        {
            HttpWebRequest request = result.AsyncState as HttpWebRequest;
            WebResponse response = null;
            try
            {
                // HttpWebRequest.EndGetResponse(IAsyncResult) - 结束对指定 URI 资源做异步请求
                //     返回值为 WebResponse 对象
                response = request.EndGetResponse(result) as HttpWebResponse;
            }
            catch (Exception ex)
            {
                _exception = ex.ToString();
            }
            // SynchronizationContext.Post(SendOrPostCallback d, Object state) - 将异步消息发送到该同步上下文中
            //     SendOrPostCallback d - System.Threading.SendOrPostCallback 委托
            //     Object state - 需要传递的参数
            _syncContext.Post(GetResponse2, response);
        }

        /// <summary>
        /// HttpWebResponse - 对指定的 URI 做出响应
        /// GetResponseStream() - 获取响应的数据流
        /// </summary>
        /// <param name="state"></param>
        private void GetResponse2(object state)
        {
            HttpWebResponse response = state as HttpWebResponse;
            if (response != null)
            {
                Stream responseStream = response.GetResponseStream();
                using (StreamReader sr = new StreamReader(responseStream))
                {
                    string xml = sr.ReadToEnd();
                    AfterSet(xml);
                }
            }
            else
            {
                MessageBox.Show(_exception);
            }

        }



        #endregion


        private void getSurveyInfo(string xml)
        {
            try
            {
                surveyCollections.Clear();
                Byte[] b = System.Text.UTF8Encoding.UTF8.GetBytes(xml);
                XDocument xele = XDocument.Load(System.Xml.XmlReader.Create(new MemoryStream(b)));
                XElement xur = (from item in xele.Descendants("Data") select item).First();
                XElement sur = (from item in xur.Descendants("SurveyInfo") select item).First();
                surveryid = int.Parse(sur.Attribute(XName.Get("ID")).Value);
                lname.Text = sur.Attribute(XName.Get("CName")).Value;
                tname.Text = sur.Attribute(XName.Get("TeacherName")).Value;
                var partNos = from item in sur.Descendants("CategoryInfo") select item;
                foreach (XElement ele in partNos)
                {
                    SurveyModel model = new SurveyModel();
                    model.categoryID = int.Parse(ele.Element(XName.Get("CategoryID")).Value);
                    model.categoryName = ele.Element(XName.Get("CategoryName")).Value;
                    XElement Options = (from item in ele.Descendants("Options") select item).First();
                    var childNos = from item in Options.Descendants("Option") select item;
                    foreach (XElement child in childNos)
                    {
                        model.options.Add(int.Parse(child.Element(XName.Get("OptionID")).Value), child.Element(XName.Get("OptionName")).Value);
                    }
                    surveyCollections.Add(model);
                }
                Setup();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
            }
        }

        private void AfterSet(string xml)
        {
            if (HtmlPage.Window.Confirm("感谢您的参与，您确定关闭窗口吗？"))
            {
                HtmlPage.Window.Invoke("CloseWindow", "");
            }
        }
        List<HashTable> valueCollections = new List<HashTable>();

        private void Setup()
        {
            valueCollections.Clear();
            foreach (SurveyModel model in surveyCollections)
            {
                TextBlock tb = new TextBlock();
                tb.FontSize = 14;
                tb.FontWeight = System.Windows.FontWeights.Bold;
                tb.Text = model.categoryName;
                optionSP.Children.Add(tb);
                Border border = new Border() { Height = 1 , BorderBrush = new SolidColorBrush(Colors.Green), BorderThickness = new Thickness(1) ,  Margin = new Thickness(0,2,0,5) };
                optionSP.Children.Add(border);
  

                StackPanel spt = new StackPanel();
                spt.MouseEnter += new MouseEventHandler(sp_MouseEnter);
                spt.MouseLeave += new MouseEventHandler(sp_MouseLeave);
                spt.Orientation = Orientation.Horizontal;
                TextBlock tt = new TextBlock() { Text = "总体评价", Width = 450, FontSize = 12 };
                spt.Children.Add(tt);
                RadRating ratingt = new RadRating() { Tag = model.categoryID };
                ratingt.ValueChanged += (s, e) =>
                    {
                        if (valueCollections.Count(a => a.Key == ("t" + (s as RadRating).Tag)) <= 0)
                        {
                            valueCollections.Add(new HashTable(){ Key = "t" + (s as RadRating).Tag,Value=  (double)e.NewValue });
                        }
                        else
                        {
                            valueCollections.Single(a => a.Key == ("t" + (s as RadRating).Tag)).Value = (double)e.NewValue;
                        }
                    };
                valueCollections.Add(new HashTable() { Key = "t" + model.categoryID.ToString(), Value = 0 });
                spt.Children.Add(ratingt);
                optionSP.Children.Add(spt);


                foreach (KeyValuePair<int, string> kvp in model.options)
                {
                    StackPanel sp = new StackPanel();
                    sp.MouseEnter += new MouseEventHandler(sp_MouseEnter);
                    sp.MouseLeave += new MouseEventHandler(sp_MouseLeave);
                    sp.Orientation = Orientation.Horizontal;
                    TextBlock t = new TextBlock() { Text = kvp.Value, Width=450 , FontSize = 12 };
                    sp.Children.Add(t);
                    RadRating rating = new RadRating() { Tag = kvp.Key };
                    rating.ValueChanged += (s, e) =>
                    {
                        if (valueCollections.Count(a => a.Key == ((s as RadRating).Tag.ToString())) <= 0)
                        {
                            valueCollections.Add(new HashTable() { Key = (s as RadRating).Tag.ToString(), Value = (double)e.NewValue });
                        }
                        else
                        {
                            valueCollections.Single(a => a.Key == ((s as RadRating).Tag.ToString())).Value = (double)e.NewValue;
                        }
                    };
                    valueCollections.Add(new HashTable() { Key = kvp.Key.ToString(), Value = 0 });
                    sp.Children.Add(rating);
                    optionSP.Children.Add(sp);
                }

                border = new Border() { Height = 2, BorderThickness = new Thickness(1), Width = 500, Margin = new Thickness(0, 2, 0, 5) };
                optionSP.Children.Add(border);
                

            }
        }

        void sp_MouseLeave(object sender, MouseEventArgs e)
        {
            (sender as StackPanel).Background = new SolidColorBrush(Colors.Transparent);
        }

        void sp_MouseEnter(object sender, MouseEventArgs e)
        {
            (sender as StackPanel).Background = new SolidColorBrush(Color.FromArgb(38, 112, 168, 223));
        }

        private void RadButton_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < valueCollections.Where(a => a.Key.Substring(0, 1) != "t").Count(); i++)
            {
                content = content + valueCollections.Where(a => a.Key.Substring(0, 1) != "t").ToList()[i].Value.ToString() + ",";
            }
            if (content.Last() ==',')
            {
                content = content.Remove(content.Length -1);
            }
            for (int i = 0; i < valueCollections.Where(a => a.Key.Substring(0, 1) == "t").Count(); i++)
            {
                comment = comment + valueCollections.Where(a => a.Key.Substring(0, 1) == "t").ToList()[i].Value.ToString() + ",";
            }
            if (comment.Last() == ',')
            {
                comment = comment.Remove(comment.Length -1);
            }
            string url = string.Format("http://{0}/tools/ajax.aspx?t=addCourseSurveyLog&id={1}&content={2}&comment={3}", App.Current.Host.Source.AbsoluteUri.Split('/')[2], surveryid,content ,comment);
            SetXML(url);
        }
    }
    public class SurveyModel
    {
        public int categoryID { get; set; }
        public string categoryName { get; set; }
        public IDictionary<int, string> options { get; set; }
        public SurveyModel()
        {
            categoryID = 0;
            categoryName = "";
            options = new Dictionary<int, string>();
        }
    }

    public class HashTable
    {
        public string Key {get;set;}
        public double Value {get;set;}



    }
}
